<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\QH\SchoolPlanStoreRequest;
use App\Http\Requests\QH\SchoolSpecStoreRequest;
use App\Models\Qh_School;
use App\Models\Qh_SchoolPlan;
use App\Models\Qh_SchoolSpec;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SchoolPlanController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = Qh_SchoolPlan::filter(request()->all())
            ->with([
                'spec' => function($q) {
                    $q->selectRaw('*');
                },
                'school' => function($q) {
                    $q->selectRaw('*');
                }
            ])
            ->orderByDesc('id')->paginate(request('perPage', 10));

        return $this->restful($list);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param SchoolPlanStoreRequest $request
     * @return JsonResponse|object
     */
    public function store(SchoolPlanStoreRequest $request)
    {
        $params = $request->validated();
        $schoolSpec = Qh_SchoolSpec::findOrFail($params['schoolSpecId']);
        if (empty($params['class'])) $params['class'] = $schoolSpec->class;
        if (empty($params['xz'])) $params['xz'] = $schoolSpec->xz;
        if (empty($params['whcd'])) $params['whcd'] = $schoolSpec->class;
        $spec = Qh_SchoolPlan::create($params);

        return $this->restful($spec);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param SchoolPlanStoreRequest $request
     * @param int $id
     * @return JsonResponse|object
     */
    public function update(SchoolPlanStoreRequest $request, int $id)
    {
        $params = $request->validated();
        $schoolSpec = Qh_SchoolSpec::findOrFail($params['schoolSpecId']);
        if (empty($params['class'])) $params['class'] = $schoolSpec->class;
        if (empty($params['xz'])) $params['xz'] = $schoolSpec->xz;
        if (empty($params['whcd'])) $params['whcd'] = $schoolSpec->class;
        $result = Qh_SchoolPlan::where('id', $id)->update($params);

        return $this->restful($result);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $result = Qh_SchoolPlan::where('id', $id)->delete();
        return $this->restful($result);
    }
}
